<template>
  <div class="hoursReg">
    <div style="display: flex">
      <jc-button
        :btn-arr="['reload', 'newy', 'remove', 'option']"
        :disab-arr="['close', 'cancel', 'using', 'copy', 'freeze', 'com1', 'com2', 'chart']"
        @refresh="getUserList"
        @newly="newly"
        @toExcel="handleExport"
        @del="delCustom"
      />
      <el-button style="margin-left: 10px;" size="mini" type="primary" @click="resetRegist">{{ $t('market.sun') }}</el-button>
    </div>
    <div class="header">
      <div class="header-name">
        <span class="inputLef">{{ $t('market.plaint') }}</span>
        <el-input v-model="departmentName" class="inputs" />
        <span class="inputLef">{{ $t('market.fdate') }}</span>
        <el-date-picker
          v-model="data1"
          size="mini"
          type="month"
          value-format="yyyy-MM"
          class="inputs"
        />
        <el-button size="mini" type="primary" class="btn" @click="searchMaterialList">
          {{ $t('btn.search') }}
        </el-button>
      </div>
    </div>
    <div class="table-content">
      <jc-table
        v-loading="loading"
        :table-data="tableData"
        :table-header="tableHeader"
        sortable
        table-selection
        :get-summaries="getSummaries"
        show-summary
        @selectionChange="selectionDatas"
        @clickRow="editSalType"
      >
        <template v-slot:btnSlot="col">
          <el-button size="mini" type="warning" @click="editSalType(col.scope.row)">{{ $t('btn.edit') }}</el-button>
        </template>
      </jc-table>
    </div>
    <div class="footer">
      <jc-pagination
        v-show="total > 0"
        :total="total"
        :page.sync="pageNum"
        :limit.sync="size"
        @pagination="getUserList"
      />
    </div>
    <!--工时登记-->
    <el-dialog
      :title="$t('menu.hoursRegister')"
      :visible.sync="addDialogVisible"
      width="500px"
      center
      :close-on-click-modal="false"
      :before-close="addHandleClose"
    >
      <el-form
        ref="ruleForm"
        :model="addRole"
        size="mini"
        label-width="100px"
      >
        <el-form-item :label="$t('market.fdate')">
          <el-date-picker
            v-model="addRole.data"
            size="mini"
            type="month"
            value-format="yyyy-MM"
            style="width: 163px"
            :disabled="isDisabled"
          />
        </el-form-item>
        <el-form-item :label="$t('market.plaint')">
          <el-select v-model="addRole.departmentId" filterable :disabled="isDisabled">
            <el-option
              v-for="iten in staffDate"
              :key="iten.fid"
              :label="iten.fname"
              :value="iten.fid"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('market.total')">
          <el-input-number v-model="addRole.sum" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item :label="$t('market.totalDate')">
          <el-input-number v-model="addRole.totalDate" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item :label="$t('market.priceSum')">
          <el-input-number v-model="addRole.priceSum" :min="0" controls-position="right" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addHandleClose">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="addRoleSubmit">{{ $t('btn.save') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryHoursRegistration,
  dleteHoursRegistration, updateHoursRegistration, reSet, insertHoursRegistration
} from '@/api/basicManagement/userslist'
import jcButton from '@/components/Button'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import { toMxAmina } from '@/components/ToMxamineState'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'

import { queryViewItem } from '@/api/marketManage/marketOrder'
export default {
  components: {
    jcButton
  },
  mixins: [autocomplete],
  data() {
    return {
      loading: false,
      addDialogVisible: false,
      isDisabled: false,
      staffDate: [],
      addRole: {},
      departmentName: '',
      data1: '',
      total: 0, // 总条目
      pageNum: 1, // 当前页
      size: 200, // 每页显示多少条数据
      tableData: [], // 列表数据
      // 表头数据
      tableHeader: [
        { label: this.$t('market.fdate'), prop: 'data', width: '120' },
        { label: this.$t('market.plaint'), prop: 'departmentName', width: '120' },
        { label: this.$t('market.total'), prop: 'sum', width: '120' },
        { label: this.$t('market.plannedAte'), prop: 'plannedAttendance' },
        { label: this.$t('market.totalDate'), prop: 'totalDate', width: '120' },
        { label: this.$t('market.plannedNumber'), prop: 'plannedNumber' },
        { label: this.$t('market.capacity'), prop: 'capacity' },
        { label: this.$t('market.averageTime'), prop: 'averageTime', width: '100' },
        { label: this.$t('market.completionTime'), prop: 'completionTime', width: '100' },
        { label: this.$t('market.planLabor'), prop: 'plannedArtificial' },
        { label: this.$t('market.actualcost'), prop: 'actualArtificial' },
        { label: this.$t('market.priceSum'), prop: 'priceSum', width: '150' },
        { label: this.$t('market.closeState'), prop: 'FCLOSESTATUSSTR', width: '100' },
        { label: this.$t('market.creator'), prop: 'createUser', width: '100' },
        { label: this.$t('market.createDate'), prop: 'createDate', width: '100' },
        { label: this.$t('market.modifier'), prop: 'modifyUser', width: '100' },
        { label: this.$t('market.modifyDate'), prop: 'modifyDate', width: '100' },
        { label: this.$t('market.handle'), type: 'btn', width: '100' }
      ],
      tableHeader1: []
    }
  },
  created() {
    this.getUserList()
    this.queryStaffType()
    this.tableHeader1 = this.tableHeader.concat(this.tableHeader1)
  },
  methods: {
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else if (this.val && this.val.length > 0) {
          const list = this.val
          const data = formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '工时登记列表')
        } else {
          queryHoursRegistration({
            pageSize: 100000,
            pageNum: 1,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.array.map(item => {
                return (toMxAmina(item))
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '工时登记列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: this.selectFbi }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.getUserList()
        this.selectFbi = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 车间
    async queryStaffType() {
      await queryViewItem({ viewName: 'SX_V_WORKSHOP' }).then(res => {
        if (res.code === 0) {
          this.staffDate = res.data.list
        }
      })
    },
    // 员工类型列表
    async getUserList() {
      this.loading = true
      const DATA = {
        pageNum: this.pageNum,
        pageSize: this.size,
        departmentName: this.departmentName,
        data: this.data1
      }
      const { data: res } = await queryHoursRegistration(DATA)
      this.tableData = res.list
      this.total = res.total
      this.loading = false
    },
    // 搜索物料
    searchMaterialList(ev) {
      this.pageNum = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.getUserList(ev.detail)
      } else {
        this.getUserList()
      }
    },
    selectionDatas(val) {
      this.selectFbi = []
      this.val = val
      this.val.forEach(res => {
        this.selectFbi.push(String(res.fid))
      })
    },
    // 删除员工类型
    delCustom() {
      this.$confirm('确认要删除么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        const api = dleteHoursRegistration
        this.toExamineFun(api)
      })
    },
    // 重置
    resetRegist() {
      const DATA = { Numbers: this.selectFbi }
      reSet(DATA).then(res => {
        if (res.code === 0) {
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 新增员工类型 关闭前回调
    addHandleClose() {
      this.addRole = {}
      this.addDialogVisible = false
    },
    // 新增
    newly() {
      this.isDisabled = false
      this.addDialogVisible = true
      this.addRole = {
        data: '',
        departmentId: '',
        totalDate: 0,
        sum: 0,
        priceSum: 0
      }
    },
    // 修改
    editSalType(ev) {
      this.addRole = {
        ...ev
      }
      this.isDisabled = true
      this.addDialogVisible = true
    },
    // 新增修改工时登记
    addRoleSubmit() {
      const api = this.addRole.fid ? updateHoursRegistration : insertHoursRegistration
      api({ ...this.addRole }).then(res => {
        if (res.code === 0) {
          this.getUserList()
          this.addHandleClose()
          this.addDialogVisible = false
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 自定义合计行
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return (Number(prev) + Number(curr)).toFixed(2)
            } else {
              return prev
            }
          }, 0)
        } else {
          sums[index] = ''
        }
      })
      sums.forEach((res, index) => {
        if (Number(sums[index]) > 0) {
          sums[index] = Number(sums[index]).toLocaleString()
        } else {
          sums[index] = ''
        }
      })
      sums[0] = '合计'
      return sums
    }
  }
}
</script>

<style scoped lang="scss">
.hoursReg {
  @include listBom;
  .header {
    .header-name {
      width: 100%;
    }
    .inputs {
      width: 163px
    }
    .btn {
      transform: translateY(5px);
      margin-left: 40px!important;
    }
    .inputLef {
      font-size: 14px;
      width: 80px;
      padding-right: 10px;
      text-align: right;
    }
  }
  .el-input::v-deep .el-input__inner {
    height: 30px;
    line-height: 30px;
    width: 176px;
  }
  .el-form {
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    width: 100%;

    .el-form-item {
      height: 35px;
      width: 100%;
      margin-bottom: 10px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
</style>
